package com.onion.auth.web.filter;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.onion.auth.exception.AuthException;
import com.onion.auth.handler.AclHandler;
import com.onion.auth.handler.PostHandler;
import com.onion.auth.support.defination.AclDefine;
import com.onion.auth.web.support.HttpAclContext;
import com.onion.auth.web.support.HttpRequestUtils;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Stack;

public class OnionAclFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(OnionAclFilter.class);

    private List<AclDefine> aclDefineChain = Lists.newArrayList();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("完成资源访问控制过滤器初始化:\r\n{}", JSON.toJSONString(aclDefineChain));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //获取Http请求Context
        HttpAclContext aclContext = HttpRequestUtils.buildAuthContext((HttpServletRequest)request);
        try{
            for(AclDefine aclDefine : aclDefineChain){
                if(!aclContext.getRequestResource().matches(aclDefine.getDefine())){
                    //URL不匹配
                    continue;
                }
                //URL匹配成功
                AclHandler aclHandler = aclDefine.getAclHandler();
                if(aclHandler.handle(aclContext)) {
                    //权限验证通过，执行下一个Filter
                    chain.doFilter(request, response);
                    return;
                }
            }
            //无权限认证
            throw new AuthException(-1, "无操作权限!");
        }finally {
            Stack<PostHandler> postHandlerStack = aclContext.getPostHandlerStack();
            if(postHandlerStack != null){
                while(!postHandlerStack.isEmpty()){
                    PostHandler postHandler = postHandlerStack.pop();
                    postHandler.postHandle(aclContext);
                }
            }
        }
    }

    @Override
    public void destroy() {
        logger.info("销毁资源访问控制过滤器：OnionAclFilter");
    }

}